package com.orangelife.webservice.base;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import org.apache.commons.httpclient.HttpStatus;

import com.orangelife.service.base.common.GeneralJsonEntity;
import com.orangelife.session.Session;
import com.orangelife.session.impl.SimpleSessionManager;
import com.orangelife.utils.LoginSessionContext;

public abstract class AbstractV1TransferService extends WebApplicationException {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7255318205708610320L;
	@Resource(name = "sessionManager")
	private SimpleSessionManager sessionManager;

	protected Session getSession(HttpServletRequest request) {
		if (request == null)
			return null;

		String id = request.getHeader(HeaderConst.ACCESS_TOKEN);
		if (id == null) {
			return null;
		}
		return sessionManager.getSession(id);
	}

	protected Session createSession() {

		return sessionManager.create();
	}

	protected void removeSession(String id) {
		sessionManager.remove(id);
	}

	protected Long getLoginuserID(HttpServletRequest request) {
		LoginSessionContext logininfo = (LoginSessionContext) getSession(
				request).getAttribute(Session.LOGIN_SESSION_CONTEXT);
		return logininfo.getuserID();
	}

	protected String getLoginUserName(HttpServletRequest request) {
		LoginSessionContext logininfo = (LoginSessionContext) getSession(
				request).getAttribute(Session.LOGIN_SESSION_CONTEXT);
		return logininfo.getLoginName();
	}

	protected Response responseByStatus(Integer status, String message)
			throws IOException {
		GeneralJsonEntity entity = new GeneralJsonEntity();
		entity.setErrCode(status);
		entity.setErrInfo(message);
		ResponseBuilder rb = Response.status(HttpStatus.SC_OK);
		rb.entity(entity);
		return rb.build();
	}

}
